package com.mm.ai.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.mm.ai.common.CommonException;
import com.mm.ai.config.OssProperties;
import com.mm.ai.service.OssService;
import com.mm.ai.utils.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * @Author：tangnaichao
 * @Date：2024/10/25 19:34
 */
@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;

    @Override
    public String uploadFile(MultipartFile multipartFile) {
        String fileUrl = null;
        InputStream inputStream = null;
        try {
            // 获取上传文件的输入流
            inputStream = multipartFile.getInputStream();

            // 生成一个唯一的文件名
            String fileName = generateUniqueFileName(multipartFile.getOriginalFilename());

            // 上传文件到指定的存储空间（bucketName）并设置文件名
            ossClient.putObject(ossProperties.getBucketName(), fileName, inputStream);

            // 构建文件的 URL 地址
            fileUrl = ossProperties.getEndpoint() + "/" + ossProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            log.error("上传文件到oss失败{}", e.getMessage());
        }
        return fileUrl;
    }

    /**
     * 生成一个唯一的文件名
     *
     * @param originalFilename 原始文件名
     * @return 新的唯一文件名
     */
    private String generateUniqueFileName(String originalFilename) {
        String uniqueFileName = UUIDUitl.generateUUID() + originalFilename.substring(originalFilename.lastIndexOf('.'));
        return uniqueFileName;
    }

    @Override
    public String downloadFile(String osskey) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(ossProperties.getBucketName(), osskey);
        OSSObject ossObject = ossClient.getObject(getObjectRequest);

        try (InputStream is = ossObject.getObjectContent()) {
            StringBuilder resultStringBuilder = new StringBuilder();
            int cp;
            while ((cp = is.read()) != -1) {
                resultStringBuilder.append((char) cp);
            }
            return resultStringBuilder.toString();
        } catch (Exception e) {
            throw new CommonException("文件不存在:{} " + e.getMessage());
        }
    }

    @Override
    public void saveFile(String osskey, String content) {
        try (InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
            ossClient.putObject(new PutObjectRequest(ossProperties.getBucketName(), osskey, is));
        } catch (IOException e) {
            throw new CommonException("保存文件失败:{} " + e.getMessage());
        }
    }
}
